import { token, logout } from "/stores/user";

export const BASE_URL = "http://139.224.103.200:9999";

// 业务错误码
const errorCode = {
  401({ msg }) {
    uni.showToast({
      title: msg || "登录失效，请重新登录",
      icon: "none",
    });
    logout();
  },
};

export default ({
  baseURL = BASE_URL,
  checkToken = true,
  timeout = 20_000,
  url = "",
  header = {},
  ...options
}) => {
  if (checkToken !== false) {
    if (!token.value) {
      logout();
      return Promise.reject("Token not found");
    }
    header["third-session"] = token.value;
  }
  return uni
    .request({
      url: `${baseURL}${url}`,
      timeout,
      header,
      ...options,
    })
    .then((res) => {
      const { code, msg } = res.data;
      if (code === 200) {
        return res.data;
      }
      uni.hideLoading();
      if (errorCode[code]) {
        errorCode[code](res.data);
      } else {
        uni.showToast({
          title: msg || "未知错误",
          icon: "none",
        });
      }
      return Promise.reject(res.data);
    });
};
